import { createRouter, createWebHistory } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { staticRoutes, layoutRoute } from './routes';
import { usePermissionStore } from '@/stores/permission';

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [...staticRoutes, layoutRoute],
  scrollBehavior: () => ({ top: 0 })
});

const whiteList = ['/login', '/404', '/front'];

router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore();
  const permissionStore = usePermissionStore();

  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 小花在线图书馆` : '小花在线图书馆';

  // 调试信息
  console.log('[路由守卫] 路径:', to.path, 'Token状态:', !!userStore.library_token);

  // 白名单检查（支持前缀匹配）
  if (whiteList.some(path => to.path.startsWith(path))) {
    return next();
  }

  // 未登录处理
  if (!userStore.library_token) {
    return next(`/login?redirect=${encodeURIComponent(to.fullPath)}`);
  }

  // 已登录处理
  if (userStore.library_token) {
    // 获取用户信息
    if (!userStore.roles.length) {
      try {
        const { data } = await userStore.getUserInfo();
        userStore.roles = data.roles;
      } catch (error) {
        userStore.logout();
        return next('/login');
      }
    }

    // 动态路由处理
    if (!permissionStore.hasGenerated) {
      await permissionStore.generateRoutes(userStore.roles);
      
      // 清除旧路由
      permissionStore.routes.forEach(route => {
        router.removeRoute(route.name);
      });

      // 添加新路由（挂载到布局路由下）
      permissionStore.routes.forEach(route => {
        router.addRoute('Layout', { // 确保布局路由有name: 'Layout'
          ...route,
          path: route.path
        });
      });

      permissionStore.setHasGenerated(true);
      return next({ ...to, replace: true });
    }

    // 禁止重复访问登录页
    if (to.path === '/login') {
      return next('/dashboard');
    }
  }

  next();
});

export default router;